/*
 * @Author: xiaosihan 
 * @Date: 2023-08-10 11:24:00 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-10-05 09:30:24
 */

import designEditor from "@/editorComponent/designEditor";
import editorStore from "@/editorComponent/editorStore";
import { message, Spin, Tooltip } from "antd";
import clsx from "clsx";
import { autorun } from "mobx";
import { useEffect, useState } from "react";
import styles from "./toolMatting.module.less";
import templateManageService from "@/api/services/templateManageService";

interface Iprops {
}

// 抠图工具
export default function ToolMatting() {

    const [hover, setHover] = useState(false);
    const [visible, setVisible] = useState(false);
    const [disable, setDisable] = useState(false);
    const [loadding, setLoadding] = useState(false);
    const [allowNumber, setAllowNumber] = useState(0);


    useEffect(() => autorun(() => {
        const { activeObjectId, lock } = editorStore;
        setDisable(lock);

        const activeObject = designEditor.fabricCanvas.getActiveObject();
        if (activeObjectId && activeObject && activeObject.type === "image") {
            setVisible(true);
        } else {
            setVisible(false);
        }
    }), []);



    return (
        <Tooltip
            title="抠图"
            placement="top"
            mouseLeaveDelay={0}
            mouseEnterDelay={0.5}
        >
            <div
                onClick={async () => {
                    const res = await templateManageService.getCutoutCtr();
                    const { allow, restNumber } = res;
                    setAllowNumber(restNumber);
                    if (allow) {
                        setLoadding(true);
                        // 对当前选中的图片进行人像抠图
                        await designEditor.matting();
                        setLoadding(false);
                    } else {
                        message.warning('人像抠图次数已用完！')
                    }
                }}
                onMouseEnter={() => {
                    setHover(true);
                }}
                onMouseLeave={() => {
                    setHover(false);
                }}
                className={clsx(styles.toolMatting, visible && styles.visible, disable && styles.disable, loadding && styles.hover)}
            >
                抠人像 {allowNumber > 0 ? `${allowNumber}` : null}{loadding && <Spin className={styles.spin} size="small" />}
            </div>
        </Tooltip>
    );

}